package com.canaan.business.controller.pc.basic;

import com.canaan.business.common.enums.basic.YNEnum;
import com.canaan.business.domain.basic.StorehouseAreaPicker;
import com.canaan.business.domain.basic.StorehouseAreaShipper;
import com.canaan.business.domain.basic.WmsStorehouseArea;
import com.canaan.business.service.basic.IStorehouseAreaPickerService;
import com.canaan.business.service.basic.IStorehouseAreaShipperService;
import com.canaan.business.service.basic.IWmsStorehouseAreaService;
import com.canaan.common.annotation.Log;
import com.canaan.common.core.controller.BaseController;
import com.canaan.common.core.domain.AjaxResult;
import com.canaan.common.core.page.TableDataInfo;
import com.canaan.common.enums.BusinessType;
import com.canaan.common.exception.ServiceException;
import com.canaan.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 库区Controller
 *
 * @author ruoyi
 * @date 2022-11-29
 */
@Api(tags = "库区管理")
@RestController
@RequestMapping("/basic/area")
public class WmsStorehouseAreaController extends BaseController
{
    @Resource
    private IWmsStorehouseAreaService wmsStorehouseAreaService;
    @Resource
    private IStorehouseAreaPickerService storehouseAreaPickerService;
    @Resource
    private IStorehouseAreaShipperService storehouseAreaShipperService;
    /**
     * 查询库区列表
     */
    @ApiOperation(value = "查询库区列表")
    @GetMapping("/list")
    public TableDataInfo list(WmsStorehouseArea wmsStorehouseArea)
    {
        startPage();
        List<WmsStorehouseArea> list = wmsStorehouseAreaService.selectWmsStorehouseAreaList(wmsStorehouseArea);
        return getDataTable(list);
    }

    /**
     * 库区导入模板
     */
    @ApiOperation(value = "库区导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<WmsStorehouseArea> util = new ExcelUtil<WmsStorehouseArea>(WmsStorehouseArea.class);
        util.hideColumn("storehouseName");
        util.importTemplateExcel(response, "库区数据");
    }

    /**
     * 导入库区列表
     */
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入库区列表")
    @Log(title = "库区", businessType = BusinessType.IMPORT)
    public AjaxResult importExcel(MultipartFile file)
    {
        List<WmsStorehouseArea> list;
        try {
            //读取excel文件数据
            ExcelUtil<WmsStorehouseArea> util = new ExcelUtil<WmsStorehouseArea>(WmsStorehouseArea.class);
            list = util.importExcel(file.getInputStream());
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("导入文件解析失败");
        }
        //初步校验数据
        if(CollectionUtils.isEmpty(list)){
            throw new ServiceException("文件缺少数据");
        }
        //文件内容的库区必填参数校验
        List<String> nos = list.stream().filter(e -> e.getNo() != null)
                .map(WmsStorehouseArea::getNo).collect(Collectors.toList());
        List<String> names = list.stream().filter(e -> e.getName() != null)
                .map(WmsStorehouseArea::getName).collect(Collectors.toList());

        Map<String,List<String>> noListMap = nos.stream().collect(Collectors.groupingBy(e -> e));
        Map<String,List<String>> nameListMap = names.stream().collect(Collectors.groupingBy(e -> e));
        if(noListMap.size() != nos.size()){
            List<String> repetitionList = noListMap.entrySet().stream().filter(e -> e.getValue().size() > 1)
                    .map(Map.Entry::getKey).collect(Collectors.toList());
            throw new ServiceException("文件内库区编号重复：" + repetitionList);
        }else if(nameListMap.size() != names.size()){
            List<String> repetitionList = noListMap.entrySet().stream().filter(e -> e.getValue().size() > 1)
                    .map(Map.Entry::getKey).collect(Collectors.toList());
            throw new ServiceException("文件内库区名称重复：" + repetitionList);
        }

        //深入校验数据和保存数据
        List<String> errorList = wmsStorehouseAreaService.importExcel(list);
        if(!errorList.isEmpty()){
            StringBuilder failureMsg = new StringBuilder();
            failureMsg.append("很抱歉，导入失败！共 ").append(errorList.size()).append(" 条数据格式不正确，错误如下：");
            for (int i = 0; i < errorList.size(); i++) {
                failureMsg.append("<br/>").append(i + 1).append("、").append(errorList.get(i));
            }
            return error(failureMsg.toString());
        }
        return success("导入成功");
    }

    /**
     * 导出库区列表
     */
    @ApiOperation(value = "导出库区列表")
    @Log(title = "库区", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmsStorehouseArea wmsStorehouseArea)
    {
        List<WmsStorehouseArea> list = wmsStorehouseAreaService.selectWmsStorehouseAreaList(wmsStorehouseArea);
        list.stream().forEach(e->{
            if (YNEnum.Y.getCode().equalsIgnoreCase(e.getWhetherMp())){
                e.setWhetherMp(YNEnum.Y.getMessage());
            }else{
                e.setWhetherMp(YNEnum.N.getMessage());
            }
            //获取拣货员
           List<StorehouseAreaPicker> pickers = storehouseAreaPickerService.storehouseAreaPickerListByAreaNo(e.getNo());
            if (!CollectionUtils.isEmpty(pickers)){
                String join = String.join(",",pickers.stream().map(StorehouseAreaPicker::getShipperName).collect(Collectors.toList()));
                e.setAreaPickerStr(join);
            }
            //获取码货员
            List<StorehouseAreaShipper> shippers = storehouseAreaShipperService.selectStorehouseAreaShipperListByAreaNo(e.getNo());
            if (!CollectionUtils.isEmpty(shippers)) {
                String join = String.join(",",shippers.stream().map(StorehouseAreaShipper::getShipperName).collect(Collectors.toList()));
                e.setAreaShipperStr(join);
            }
        });
        ExcelUtil<WmsStorehouseArea> util = new ExcelUtil<WmsStorehouseArea>(WmsStorehouseArea.class);
        util.exportExcel(response, list, "库区数据");
    }

    /**
     * 获取库区详细信息
     */
    @ApiOperation(value = "获取库区详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wmsStorehouseAreaService.selectWmsStorehouseAreaById(id));
    }

    /**
     * 新增库区
     */
    @ApiOperation(value = "新增库区")
    @Log(title = "库区", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WmsStorehouseArea wmsStorehouseArea)
    {
        return success(wmsStorehouseAreaService.insertWmsStorehouseArea(wmsStorehouseArea));
    }

    /**
     * 修改库区
     */
    @ApiOperation(value = "修改库区")
    @Log(title = "库区", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WmsStorehouseArea wmsStorehouseArea)
    {
        return toAjax(wmsStorehouseAreaService.updateWmsStorehouseArea(wmsStorehouseArea));
    }

    /**
     * 删除库区
     */
    @ApiOperation(value = "删除库区")
    @Log(title = "库区", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(wmsStorehouseAreaService.deleteWmsStorehouseAreaByIds(ids));
    }
}
